package org.o14x.alpha.domain;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class NavigationHistory {
	/**
	 * File list.
	 */
	private List<File> fileList;

	/**
	 * Position in the file list.
	 */
	private int index = -1;

	/**
	 * Creates a new instance of NavigationHistory.
	 */
	public NavigationHistory() {
		fileList = new ArrayList<File>();
	}

	/**
	 * Memorizes a file in the history.
	 * 
	 * @param file The file to memorize.
	 */
	public void memorize(File file) {
		if (index == -1 || !fileList.get(index).equals(file)) {
			index++;
			fileList.subList(index, fileList.size()).clear();
			fileList.add(file);
		}

	}

	/**
	 * Gets the previous file in the history.
	 * 
	 * @return The previous file in the history or null if there is no previous file.
	 */
	public File back() {
		File file = null;

		if (index > 0) {
			index--;
			file = fileList.get(index);
			if (!file.exists()) {
				fileList.remove(index);
				file = back();
			}
		}

		return file;
	}

	/**
	 * Gets the next file in the history.
	 * 
	 * @return The next file in the history or null if there is no next file.
	 */
	public File next() {
		File file = null;

		if (index < fileList.size() - 1) {
			index++;
			file = fileList.get(index);
			if (!file.exists()) {
				index--;
				fileList.remove(index);
				file = next();
			}
		}

		return file;
	}
}
